package com.asktgapp.user.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.eventbus.WebEvent;
import com.asktgapp.model.StartPagePicVO;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.utils.MCountDownTimer;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.hyphenate.chat.EMClient;

import java.util.HashMap;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author chenbixin
 * @Title: {标题}
 * @Description:{描述}
 * @date 2017/6/27
 */
public class SplashActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private static final int sleepTime = 5500;
    private ImageView mImg;
    private TextView mTime;
    private String url;
    private TimeCount mTimeCount;
    private StartCount mStartCount;
    private boolean Permissions = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);


        if (!MyApplication.getInstance().showSplash) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }else {
            mImg = (ImageView) findViewById(R.id.iv_splash_img);
            mTime = (TextView) findViewById(R.id.tv_skip);
            mTimeCount = new TimeCount(1200, 1000);
//        mStartCount = new StartCount(3000, 1000);
//        mStartCount.start();
            getPermissions();
//        Log.i("pwd", Util.encodeMD5("123456"));
//        getPic();
//        EMClient.getInstance().addConnectionListener(connectionListener);
//            MyApplication.getInstance().showSplash = false;

            mTime.setVisibility(View.VISIBLE);
            mTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTimeCount.cancel();
                    doSkip();
                }
            });
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    public void getPer() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.READ_PHONE_STATE};
            ActivityCompat.requestPermissions(SplashActivity.this, mPermissionList, 123);
        }
    }

    private void getPic() {
//        getPer();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<StartPagePicVO>>> call = apiservice.getStartPagePic(params);
        call.enqueue(new Callback<ApiResponseBody<List<StartPagePicVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<StartPagePicVO>>> call, Response<ApiResponseBody<List<StartPagePicVO>>> response) {
                if (response.isSuccessful()) {
                    List<StartPagePicVO> list = response.body().getResult();
                    showPic(list);
                } else {
                    Toast.makeText(SplashActivity.this, response.raw().message(), Toast.LENGTH_SHORT).show();
                }
                mTime.setVisibility(View.VISIBLE);
                mTimeCount.start();
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<StartPagePicVO>>> call, Throwable t) {
                ApiException exception = ExceptionHandle.handleException(t);
                if (exception.isNetConnected()) {
                }
                mTimeCount.start();
                mTime.setVisibility(View.VISIBLE);
            }
        });


        HashMap param = new HashMap();
        param.put("userid", PreferencesUtil.getString(SplashActivity.this, PreferencesUtil.USER_ID));
        param.put("ymToken", MyApplication.UmengToken);
        Call<ApiResponseBody> call1 = apiservice.updatePushToken(param);
        call1.enqueue(new Callback<ApiResponseBody>() {
                          @Override
                          public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                              if (response.isSuccessful()) {
                                  Log.i("login", "Splashactivity::token上传成功！");
                              } else {
                              }
                          }

                          @Override
                          public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                              Log.i("login", "Splashactivity::token上传失败！");
                          }
                      }
        );
    }

    private void showPic(List<StartPagePicVO> url) {
        if (url.size() > 0) {
            ImageDisplayUtil.LoadNetImageWithUrl(mImg, this, url.get(0).getContent());
        }
        mTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTimeCount.cancel();
                doSkip();
            }
        });
        mTime.setVisibility(View.VISIBLE);


    }


    class TimeCount extends MCountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (mTime == null)
                return;
            doSkip();
            Log.i("main", "onFinish: 打开一次APP" + System.currentTimeMillis());
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            if (mTime == null)
                return;
//            mTime.setVisibility(View.INVISIBLE);
            if (millisUntilFinished < 1000) {
                mTime.setText("跳过 " + "0秒");
            } else
                mTime.setText("跳过 " + millisUntilFinished / 1000 + "秒");
        }
    }

    class StartCount extends MCountDownTimer {
        public StartCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
//            getPic();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }

    private void doSkip() {
//        String userid = PreferencesUtil.getString(this, PreferencesUtil.USER_ID);
//        if (MyApplication.userIdIsEmpty(this)) {
//            startActivity(new Intent(this, LoginActivity.class));
//        } else
//        startActivity(new Intent(this, MainActivity.class));
        if (Permissions) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }else {
            new AppSettingsDialog
                    .Builder(this)
                    .setRationale("您未授予程序相关权限，可能会导致部分功能无法正常使用，是否打开设置进行授权")
                    .setPositiveButton("好")
                    .build()
                    .show();
        }
    }

    private void getPermissions() {
        EasyPermissions.requestPermissions(this,
                "应用程序将要获取以下权限：内存读取权限,本地相册读取及手机状态权限",
                0,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA);

    }

    //    当权限被成功申请的时候执行回调，requestCode是代表你权限请求的识别码，list里面装着申请的权限的名字：
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        switch (requestCode) {
            case 0:
                MyApplication.getInstance().READ_PHONE_PERMISSION = true;
                MyApplication.getInstance().showSplash = false;
                Permissions= true;
                mTimeCount.start();
                mTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mTimeCount.cancel();
                        doSkip();
                    }
                });
                break;
        }
    }

    //当权限申请失败的时候执行的回调
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        MyApplication.getInstance().READ_PHONE_PERMISSION = false;
        Permissions= false;
        new AppSettingsDialog
                .Builder(this)
                .setRationale("您未授予程序相关权限，可能会导致部分功能无法正常使用，是否打开设置进行授权")
                .setPositiveButton("好")
                .build()
                .show();
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
////            Toast.makeText(this,"已拒绝权限" + sb + "并不再询问",Toast.LENGTH_SHORT);
//
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
